export const uploadFile = (filePath) => {
  const app = getApp();
  const { appId, root } = app.$app;

  return new Promise((resolve, reject) => {
    const headers = {
      "weapp-appid": appId,
      "weapp-env": __wxConfig.envVersion,
    };

    const jwt = wx.getStorageSync("KEY_JWT");
    if (jwt) {
      headers.Authorization = `Bearer ${jwt}`;
    }

    wx.uploadFile({
      url: `${root}/upload/local-save`,
      filePath: filePath,
      name: "file",
      header: headers,
      formData: {
        openId: wx.getStorageSync("openId"),
        unionId: wx.getStorageSync("unionId"),
      },
      success: function (res) {
        console.log("login.uploadFile", res);
        resolve(JSON.parse(res.data));
      },
      fail: function (e) {
        reject(e);
      },
    });
  });
};

export const uploadImg = (count=9, sourceType=['album', 'camera']) => {
  const app = getApp();
  const { appId, root } = app.$app;

  return new Promise((resolve, reject) => {
    wx.chooseMedia({
      count,
      sizeType: ['compressed'],
      // sourceType,
      success: (res) => {
        console.log(res);
        const files = res.tempFiles.map(item => item.tempFilePath);
        const all = files.every(file => /\.(jpg|png|jpeg)$/i.test(file));

        if(!all) {
          wx.showToast({
            title: '请上传正确的图片格式！',
            icon: 'none'
          });
        }

        wx.showLoading({
          icon: 'none',
          title: '上传中...',
        });

        const headers = {
          "weapp-appid": appId,
          "weapp-env": __wxConfig.envVersion,
        };

        const jwt = wx.getStorageSync("KEY_JWT");
        if (jwt) {
          headers.Authorization = `Bearer ${jwt}`;
        }

        let index = 0;
        const newFiles = [];

        files.forEach(file => {
          wx.uploadFile({
            url: `${root}/upload/local-save`,
            filePath: file,
            name: "file",
            header: headers,
            formData: {
              openId: wx.getStorageSync("openId"),
              unionId: wx.getStorageSync("unionId"),
            },
            success: function (res) {
              const data = JSON.parse(res.data);
              const filePath = data.url
              newFiles.push(filePath);
            },
            fail: function (e) {
              console.log(file + '上传失败');
              reject(e);
            },
            complete: res => {
              if(++index === files.length){
                wx.hideLoading();
                resolve(newFiles);
              }
            }
          });
        });
      }
    })
  })
};
